<style lang="scss">
.selfselect{
    .sel-btn{
        height: 25px;
        padding: 0 5px;
    }
    .sel-search{
        .ivu-input{
            border:none;
            border-bottom:1px solid #ddd;
        }
        .ivu-input:hover,.ivu-input:focus{
            border:none;
            border-bottom:1px solid #2d8cf0;
            box-shadow:none;
        }
    }
    .sel-options-box{
        width: unset;
        min-width: 100px;
        transform-origin: center top;
        z-index: 1;
        position: absolute;
        padding:0 5px;
    }
    .sel-select-dropdown {
        position: absolute;
        z-index: 5;
        border: 1px solid #e6e8eb;
        border-radius: 4px;
        background-color: #fff;
        -webkit-box-shadow: 0 8px 16px 0 rgb(0 0 0 / 16%);
        box-shadow: 0 8px 16px 0 rgb(0 0 0 / 16%);
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        margin: 5px 0;
    }
    .sel-options-li{
        align-items: center;
        height: 32px;
        line-height: 32px;
        outline: 0;
        cursor: pointer;
        .sel-check{
            padding:0 12px;
            width:94%;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
    .sel-options-li:hover{
        background-color: #f5f6f9;
    }
    .activeOption{
        background-color: #f5f6f9;
    }
}
</style>
<template>
    <div :id="key">
        <!-- 第二种，下拉带分组全选和搜索 -->
        <div :class="class" class="selfselect" v-if="isGroup" ref="showGroupPanel" >
            <div>
                <Input
                :placeholder="placeholder"
                v-model="readgroupvalue"
                readonly="true"
                @mouseup="clickgroupDown"
                
                >
                    <template #suffix v-if="showgroupdown">
                        <Icon type="ios-arrow-down" />
                    </template>
                    <template #suffix v-else-if="!showgroupdown">
                        <Icon type="ios-arrow-up" />
                    </template>
                </Input>
            </div>
            <div v-if="showgroupList" class="sel-options-box sel-select-dropdown" style="max-width:350px;min-width:180px">
                <!-- 搜索输入 -->
                <Input 
                class="sel-search"
                placeholder="搜索内容"
                v-model="choosegroupvalue"
                @on-change="changeGroupValue"
                >
                    <template #prefix>
                        <Icon type="ios-search" />
                    </template>
                </Input>
                <!-- 正常下拉展示 -->
                <div v-show="!showgroupBox" style="width:350px">
                    <!-- 全选按钮 -->
                    <div style="max-height:200px;overflow:auto;width:49%;float:left" >
                        <li @click="handleCheckGroupAllChange" class="sel-options-li">
                            <Checkbox class="sel-check" :indeterminate="groupindeterminate" v-model="checkAllgroup" @on-change="handleCheckGroupAllChange">全选</Checkbox>
                        </li>
                        <ul ref="selop">
                            <li v-for="(item,index) in copygroupoptions" :key="index">
                                <span @mouseenter="itemhouver(index)" class="groupLi" :class="{'groupacitve':houverIndex == index}">
                                    <Checkbox v-model="item.checkGroup" :indeterminate="item.oneindeterminate" @on-change="handleCheckGroupChange(item,index)" style="margin-left:12px;"><span >{{item.groupName}}</span></Checkbox>
                                    <Icon type="ios-arrow-forward" />
                                </span>
                            </li>
                        </ul>
                    </div>
                    <div style="display:inline-block;width:1px;background:#ddd;height:185px"></div>
                    <!-- 展示侧边的内容 -->
                    <div v-for="(item,index) in copygroupoptions" :key="item.value" style="width:49%;float:right;max-height:195px;overflow:auto" v-show="houverIndex == index">
                        <CheckboxGroup v-model="biddingGroupStage" @on-change="handleGroupOneItem(item)">
                            <ul >
                                <li v-for="item in item.groupOptions" :key="item.value">
                                    <Checkbox :label="item.value" >{{item.label}}</Checkbox>
                                </li>
                            </ul>
                        </CheckboxGroup>
                    </div>
                </div>
                <!-- 搜索之后的展示 -->
                <div v-show="showgroupBox">
                    <div style="max-height:200px;overflow:auto">
                        <li @click="handleCheckAllChangeSearch" class="sel-options-li">
                            <Checkbox class="sel-check" :indeterminate="newgroupindeterminate" v-model="checkAllSearch" @on-change="handleCheckAllChangeSearch">全选</Checkbox>
                        </li>
                        <ul ref="selop">
                            <CheckboxGroup v-model="biddingStageSearch" @on-change="checkSearchOptionChange">
                                <li 
                                class="sel-options-li"
                                v-for="(item,index) in searchList" 
                                :key="index" 
                                :data-index="index"
                                >
                                    <Checkbox  class="sel-check" :label="item.value">{{item.label}}</Checkbox>
                                </li>
                            </CheckboxGroup>
                        </ul>
                    </div>
                </div>
                <div class="text-right margin-bottom-5" style="border-top:1px solid #ddd">
                    <Button class="sel-btn margin-right-5" @click="groupcancel">取消</Button>
                    <Button class="sel-btn" type="primary" @click="groupconfirm">确定</Button>
                </div>
            </div>
        </div>
        <!-- 第一种，下拉带全选和搜索 -->
        <div :class="class" class="selfselect" v-else ref="showPanel">
            <div>
                <Input
                :placeholder="placeholder"
                v-model="readvalue"
                readonly="true"
                @mouseup="clickDown"
                >
                    <template #suffix v-if="showdown">
                        <Icon type="ios-arrow-down" />
                    </template>
                    <template #suffix v-else-if="!showdown">
                        <Icon type="ios-arrow-up" />
                    </template>
                </Input>
            </div>
            <div v-if="showList" class="sel-options-box sel-select-dropdown" style="min-width:150px;max-width: 230px;" :style="vstyle">
                <!-- 搜索输入 -->
                <Input 
                ref="inAutofocus"
                class="sel-search"
                placeholder="搜索内容"
                v-model="choosevalue"
                @on-change="changeValue"
                @on-keydown="chooseItem"
                @on-enter="selectOption"
                >
                    <template #prefix>
                        <Icon type="ios-search" />
                    </template>
                </Input>
                <!-- 全选按钮 -->
                <div style="max-height:200px;overflow:auto" ref="selop" class="select-option-box">
                    <li @click="handleCheckAllChange" class="sel-options-li">
                        <Checkbox class="sel-check" :indeterminate="indeterminate" v-model="checkAll" @on-change="handleCheckAllChange">全选</Checkbox>
                    </li>
                    <ul class="select-option">
                        <CheckboxGroup v-model="biddingStage" @on-change="checkItemOptionChange">
                            <li 
                            class="sel-options-li"
                            v-for="(item,index) in copyoptions" 
                            :key="index" 
                            :data-index="index"
                            >
                                <Checkbox  class="sel-check" :label="item.value">{{item.label}}</Checkbox>
                            </li>
                        </CheckboxGroup>
                    </ul>
                </div>
                <div class="text-right margin-bottom-5" style="border-top:1px solid #ddd">
                    <Button class="sel-btn pull-left margin-top-5" @click="clearAll">清空选项</Button>
                    <Button class="sel-btn margin-right-5" @click="cancel">取消</Button>
                    <Button class="sel-btn" type="primary" @click="confirm">确定</Button>
                </div>
            </div>
        </div>
        
    </div>
</template>

<script>
    export default {
        props:{
            // 下拉选项
            options: {
                type: Array,
                default: () => []
            },
            optionsGroup: {
                type: Array,
                default: () => []
            },
            vstyle:String,
            class:String,
            placeholder:String,
            modelValue:Object,
            isGroup:Boolean, //是否展示group下拉全选
            key:String,
        },
        data(){
            return {
                readvalue:'',
                readgroupvalue:'',
                choosevalue:'',
                choosegroupvalue:'',
                showdown:true,
                showList:false,
                showgroupdown:true,
                showgroupList:false,
                checkAll: false, //是否全选
                checkAllgroup: false, //group全选
                isIndeterminate: false, //全选复选框标识     
                flagmouseout:false,
                indeterminate:false,
                groupindeterminate:false,
                newgroupindeterminate:false,
                chooseDatas:[],
                biddingStage:[],
                biddingGroupStage:[],
                copyoptions:[],
                copygroupoptions:[],
                showgroupBox:false,

                houverIndex:-1,
                itemHoverIndex:0,
                searchList:[],

                checkAllSearch:false,
                biddingStageSearch:[],
                dataarr:[],
                
            }
        },
        mounted(){
            document.addEventListener('click', (e) => {
                if (this.$refs.showGroupPanel) {
                    let isSelf = this.$refs.showGroupPanel.contains(e.target)
                    if (!isSelf) {
                        if(!this.readgroupvalue){
                            this.biddingGroupStage = []
                        }
                        this.showgroupdown = true;
                        this.showgroupList = false;
                    }
                }
                if (this.$refs.showPanel) {
                    let isSelf = this.$refs.showPanel.contains(e.target)
                    if (!isSelf) {
                        if(!this.readvalue){
                            this.biddingStage = []
                        }
                        this.showdown = true;
                        this.showList = false;
                    }
                }
            })
            this.$bus.on("changereset", value => {
                if(value === 'reset'){
                    this.clearAll()
                }

            });
        },
        watch:{
            options:{
                deep: true,
                immediate: true,
                handler(newas,oldss){
                    this.copyoptions =  this.options.concat()
                }
            },
            optionsGroup:{
                deep: true,
                immediate: true,
                handler(newas,oldss){
                    this.optionsGroup.map(item=>{
                        item.checkGroup = false
                    })
                    this.copygroupoptions = this.optionsGroup.concat()
                    this.copygroupoptions.map((item) => {
                        item.groupOptions.map(json =>{
                            this.dataarr.push(json.value) 
                        })
                    })
                }
            },
            modelValue:function(val){
                if(!val){
                    this.clearAll()
                }
            },
        },
        
        methods:{
            clearAll(){
                this.biddingStage = [];
                this.biddingGroupStage = [];
                this.biddingStageSearch = [];
                this.readvalue='';
                this.readgroupvalue='';
                this.choosegroupvalue='';
                this.indeterminate = null;
                this.groupindeterminate = null;
                this.newgroupindeterminate = null;
                this.copygroupoptions.map((item) => {
                    item.checkGroup = false;
                    item.oneindeterminate = null;
                })
                this.checkAllgroup = false;
                this.checkAllSearch = false;
                this.checkAll = false;
                this.showgroupBox = false;
                this.$emit('update:modelValue',this.biddingStage)
            },
            // 进行分组加载
            loadGroup(datalist){
                let result = [];
                let groupitem;
                for(var i =0;i<datalist.length;i++){
                    if(i % 500 == 0){
                        groupitem !=null && result.push(groupitem);
                        groupitem = []
                    }
                    groupitem.push(datalist[i])
                }
                result.push(groupitem);
                return result;
            },
            loadOne(datalist){
                this.copyoptions = []
                let groups = this.loadGroup(datalist);
                this.loadPart(groups[0])
            },
            loadAll(datalist){
                this.copyoptions = []
                let groups = this.loadGroup(datalist);
                let _this = this;
                for(var i=0;i<groups.length;i++){
                    window.setTimeout(function(){
                        let groupone = groups[i];
                        let index = i + 1;

                        _this.loadPart(groupone,index)
                    }(),10)
                }
            },
            loadPart(groupone,index){
                for(var i=0;i<groupone.length;i++){
                    this.copyoptions.push(groupone[i])
                }
            },
            chooseItem(event){
                if(this.copyoptions.length === 0) return;
                // if(!hasFocusOption){
                    if(event.keyCode === 40){
                        this.itemHoverIndex++;
                        console.log(this.itemHoverIndex,'this.itemHoverIndex')
                        // 重新回到第一个
                        if(this.itemHoverIndex === this.copyoptions.length){
                            this.itemHoverIndex = 0
                        }
                        // 超过当前的高度就开始滚动
                        if((this.itemHoverIndex+1)*32>=document.querySelector('.select-option-box').scrollTop+200){
                            document.querySelector('.select-option-box').scrollTop = (this.itemHoverIndex+1)*32-200
                        }else if(this.itemHoverIndex === 0) document.querySelector('.select-option-box').scrollTop = 0
                    }else if(event.keyCode === 38){
                        this.itemHoverIndex--;
                        if(this.itemHoverIndex<0){
                            this.itemHoverIndex = this.copyoptions.length-1
                        }
                        if((this.itemHoverIndex+1)*32-32<=document.querySelector('.select-option-box').scrollTop){
                            document.querySelector('.select-option-box').scrollTop = (this.itemHoverIndex+1)*32-32
                        }else if(this.itemHoverIndex === this.copyoptions.length-1){
                            document.querySelector('.select-option-box').scrollTop = (this.itemHoverIndex+1)*32-200
                        }
                    }
                // }else{
                //     if((this.itemHoverIndex+1)*32>200){
                //         document.querySelector('.select-option-box').scrollTop = (this.itemHoverIndex+1)*32-200
                //     }else{
                //         document.querySelector('.select-option-box').scrollTop = 0
                //     }
                // }

                // 整个下拉加入class
                let optionItems = this.$refs.selop.querySelectorAll('.sel-options-li');
                optionItems.forEach((item,index)=>{
                    item.classList.remove('activeOption')
                    if(index===this.itemHoverIndex) item.classList.add('activeOption')
                })
            },
            selectOption(){
                let aavalue = this.copyoptions[this.itemHoverIndex-1].value
                if(this.biddingStage.indexOf(aavalue)>-1){
                    this.biddingStage = this.biddingStage.filter(item=>item!=aavalue)
                }else{
                    this.biddingStage.push(aavalue)
                }
            },
            clickDown(){
                this.showdown = !this.showdown;
                this.showList = !this.showList;
                if(this.showList){
                    setTimeout(() => {
                        this.$refs.inAutofocus.focus()
                    }, 10);
                }
                this.itemHoverIndex = 0;

                // 判断是否有选中,不带分组的
                if(this.readvalue===''){
                    this.choosevalue = '';
                    this.checkAll = false;
                    if(this.options.length>500){
                        this.loadOne(this.options);
                        setTimeout(() => {
                            this.loadAll(this.options);
                        }, 100);
                    }else{
                        this.copyoptions =  this.options.concat();
                    }
                }else{
                    if(this.biddingStage.length === this.copyoptions.length){
                        this.checkAll = true;
                    }else{
                        this.checkAll = false;
                        this.indeterminate = this.biddingStage.length>0?true:null;
                    }
                }
            },
            clickgroupDown(){
                this.showgroupdown = !this.showgroupdown;
                this.showgroupList = !this.showgroupList;
            },
            changeValue(val){
                this.copyoptions = this.options.filter(item=>{
                    return item.label.toLowerCase().includes(this.choosevalue.toLowerCase())
                })
            },
            // 正常下拉的全选
            handleCheckAllChange(val){
                const data = this.options.map(item => {
                    return item.value
                })
                this.biddingStage = val ? data : [];
                this.indeterminate = val ? false : null;
            },
            // 正常下拉的单条选择
            checkItemOptionChange(data){
                const checkedCount = this.biddingStage.length;
                this.checkAll = checkedCount === this.copyoptions.length;
                if(!this.checkAll){
                    if(checkedCount>0){
                        this.indeterminate = true
                    }else{
                        this.indeterminate = false
                    }
                }else{
                    this.indeterminate = false
                }
            },
            confirm(){
                if(this.biddingStage.length>0){
                    let aa = this.options.filter(item=>{
                        if(item.value==this.biddingStage[0]){
                            return item 
                        }
                    })[0]
                    let bb = this.biddingStage.length-1
                    if(bb >0 ){
                        this.readvalue = aa.label+' +'+bb
                    }else{
                        this.readvalue = aa.label
                    }
                    this.$emit('update:modelValue',this.biddingStage)
                    this.showList = false;
                }else{
                    this.readvalue = '';
                    this.showList = false;
                }
                this.choosevalue = '';
                this.indeterminate = null;
                this.copyoptions =  this.options.concat();
            },
            cancel(){
                this.choosevalue = '';
                this.indeterminate = null;
                this.copyoptions =  this.options.concat();
                this.showList = false;
            },
            // 组合下拉输入查询的逻辑
            changeGroupValue(val){
                let value = val.data
                if(value){
                    this.showgroupBox = true;
                }else{
                    this.showgroupBox = false;
                }
                // 搜索之后重新进行数组整合
                this.copygroupoptions.forEach(item=>{
                    item.groupOptions.map(json=>{
                        if(json.label.includes(value)){
                            let data = {
                                label:item.groupName+'/'+json.label,
                                value:json.value
                            }
                            this.searchList.push(data)
                        }
                    })
                    
                })
            },
            // 组合下拉的全选
            handleCheckGroupAllChange(val){
                // 找到全部数据
                if(val){
                    const data = []
                    this.copygroupoptions.map((item) => {
                        item.checkGroup = true;
                        item.oneindeterminate = null;
                        item.groupOptions.map(json =>{
                            data.push(json.value) 
                        })
                    })
                    this.groupindeterminate = null;
                    this.biddingGroupStage = data
                }else{
                    this.copygroupoptions.map((item) => {
                        item.checkGroup = false;
                    })
                    this.groupindeterminate = null;
                    this.biddingGroupStage = []
                }
            },
            // 组合选择左边点击
            handleCheckGroupChange(item,index){
                const arr = this.copygroupoptions.find((f,findex)=>findex===index).groupOptions.map(m=>m.value)
                let val = item.checkGroup
                if(val){
                    item.oneindeterminate = null;
                    arr.forEach(item=>{
                        if(!this.biddingGroupStage.includes(item)){
                        this.biddingGroupStage.push(item)
                        }
                    })
                    }else {
                    this.biddingGroupStage.forEach((item,index)=>{
                        if(arr.includes(item)){
                        this.biddingGroupStage.splice(index,1,'')
                        }
                    })
                }
                this.biddingGroupStage = this.biddingGroupStage.filter(f=>f!=='')
                
                
                if(this.biddingGroupStage.length === this.dataarr.length){
                    this.checkAllgroup = true;
                    this.groupindeterminate = null;
                }else{
                    this.biddingGroupStage.length>0 ? this.groupindeterminate = true : this.groupindeterminate = false
                    if(this.biddingGroupStage.length==0){
                        this.checkAllgroup = false;
                        this.groupindeterminate = null
                    }
                }
            },
            // 组合选择单个的时候
            handleGroupOneItem(item){
                const arr = item.groupOptions.map(m=>m.value)
                let flag = arr.every((v) => {
                    return this.biddingGroupStage.some(s => s === v)
                })
                let oneflag = arr.some((v) => {
                    return this.biddingGroupStage.some(s => s === v)
                })
                
                if(flag){
                    item.oneindeterminate = null;
                    item.checkGroup = true;
                }else{
                    if(oneflag){
                        item.oneindeterminate = true;
                        item.checkGroup = false;
                        this.groupindeterminate = true;
                    }else{
                        item.oneindeterminate = false;
                        item.checkGroup = false;
                    }
                }
                if(this.biddingGroupStage.length === this.dataarr.length){
                    this.checkAllgroup = true;
                    this.groupindeterminate = null;
                }
            },
            
            itemhouver(index){
                this.houverIndex = index
            },
            // 组合下拉的查询之后新的全选方法
            handleCheckAllChangeSearch(val){
                const data = this.searchList.map(item => {
                    return item.value
                })
                this.biddingStageSearch = val ? data : [];
                this.newgroupindeterminate = val ? false : null;
            },
            // 组合下拉的查询之后新的单条选择
            checkSearchOptionChange(){
                const checkedCount = this.biddingStageSearch.length;
                this.checkAllSearch = checkedCount === this.searchList.length;
                if(!this.checkAllSearch){
                    if(checkedCount>0){
                        this.newgroupindeterminate = true
                    }else{
                        this.newgroupindeterminate = false
                    }
                }else{
                    this.newgroupindeterminate = false
                }
            },
            groupconfirm(){
                // 筛选之后的下拉
                if(this.showgroupBox){
                    if(this.biddingStageSearch.length>0){
                        let oneitem = this.searchList.filter(item=>{
                            if(item.value==this.biddingStageSearch[0]){
                                return item 
                            }
                        })[0]
                        let bnum = this.biddingStageSearch.length-1
                        if(bnum >0 ){
                            this.readgroupvalue = oneitem.label+' +'+bnum
                        }else{
                            this.readgroupvalue = oneitem.label
                        }
                        this.$emit('update:modelValue',this.biddingStageSearch)
                        this.showgroupList = false;
                    }else{
                        this.readgroupvalue = '';
                        this.showgroupList = false;
                    }
                }else{
                    if(this.biddingGroupStage.length>0){
                        let oneitem = null
                        this.optionsGroup.map(item=>{
                            item.groupOptions.map(json=>{
                                if(json.value==this.biddingGroupStage[0]){
                                    oneitem = {
                                        item:item.groupName,
                                        json:json
                                    } 
                                }
                            })
                        })[0]
                        let bnum = this.biddingGroupStage.length-1;
                        if(bnum >0 ){
                            this.readgroupvalue = oneitem.item + '/' +oneitem.json.label+' +'+bnum
                        }else{
                            this.readgroupvalue = oneitem.item + '/' +oneitem.json.label
                        }
                        this.$emit('update:modelValue',this.biddingGroupStage)
                        this.showgroupList = false;
                    }else{
                        this.readgroupvalue = '';
                        this.showgroupList = false;
                    }
                }
            },
            groupcancel(){
                this.choosegroupvalue = ''
                this.showgroupList = false;
            }
        }
    }
</script>